#!/bin/bash

# 加载路径配置
source "$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)/../config/paths.conf"

TIMESTAMP=$1
REPORT_FILE="$REPORTS_DIR/final_report_$TIMESTAMP.txt"

echo "生成最终监控报告..."

cat > $REPORT_FILE << EOF
=========================================
流量监控最终报告
生成时间: $(date)
监控会话: $TIMESTAMP
主机名: $(hostname)
=========================================

EOF

# 汇总资源使用情况
if [ -f "$LOG_DIR/resource_usage_$TIMESTAMP.log" ]; then
    echo "=== 资源使用统计 ===" >> $REPORT_FILE
    grep "系统负载" "$LOG_DIR/resource_usage_$TIMESTAMP.log" | tail -5 >> $REPORT_FILE
    echo "" >> $REPORT_FILE
    
    echo "=== tcpdump资源使用 ===" >> $REPORT_FILE
    grep "tcpdump资源使用" -A 1 "$LOG_DIR/resource_usage_$TIMESTAMP.log" | tail -10 >> $REPORT_FILE
    echo "" >> $REPORT_FILE
fi

# 连接数统计
if [ -f "$CONNECTIONS_DIR/connections_count_$TIMESTAMP.log" ]; then
    echo "=== 连接数统计 ===" >> $REPORT_FILE
    awk '{print $NF}' "$CONNECTIONS_DIR/connections_count_$TIMESTAMP.log" | \
    awk 'BEGIN {max=0; min=999999; sum=0; count=0} 
         {if($1>max) max=$1; if($1<min) min=$1; sum+=$1; count++} 
         END {printf "平均连接数: %.1f\n最大连接数: %d\n最小连接数: %d\n", sum/count, max, min}' >> $REPORT_FILE
    echo "" >> $REPORT_FILE
fi

# 磁盘使用情况 - 修复：使用动态路径
echo "=== 磁盘使用情况 ===" >> $REPORT_FILE
echo "系统根目录 (/):" >> $REPORT_FILE
df -h / | awk 'NR==1 || NR==2' >> $REPORT_FILE
echo "" >> $REPORT_FILE

echo "监控目录 ($BASE_DIR):" >> $REPORT_FILE
df -h "$BASE_DIR" | awk 'NR==1 || NR==2' >> $REPORT_FILE
echo "" >> $REPORT_FILE

# 生成的日志文件
echo "=== 生成的日志文件 ===" >> $REPORT_FILE
find $LOG_DIR -name "*$TIMESTAMP*" -type f | while read file; do
    size=$(du -h "$file" | cut -f1)
    echo "  $file ($size)" >> $REPORT_FILE
done

echo "" >> $REPORT_FILE
echo "=== 报告生成完成 ===" >> $REPORT_FILE

echo "最终报告已生成: $REPORT_FILE"